<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import type { DeptModelArray, DeptModel } from '@/api/model/model'
import { queryDeptList, addDept, getDeptById, updateDeptById, deleteDeptById } from '@/api/dept/index'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

// 部门列表
let deptList = ref<DeptModelArray>([])
// 在生命周期回调中去查询服务端的接口
onMounted(() => {
    query();
});
async function query() {
    const res = await queryDeptList();
    deptList.value = res.data
}
// 新增修改弹框的标题
const dialogTitle = ref('新增部门')
// 是否展示弹框
let dialogFormVisible = ref(false)
// 弹框中的数据
let form = ref<DeptModel>({
    name: ""
})
// 打开新增的弹框
function openAdd() {
    dialogFormVisible.value = true;
    dialogTitle.value = "新增部门"
}

// 调用新增或者修改接口
function doAddOrUpdate(formEl: (FormInstance | undefined)) {
    // 做表单的校验
    if (!formEl) {
        return;
    }
    // 必须await，异步校验
    formEl.validate((valid) => {
        if (valid) {
            // 校验通过
            afterFormCheckSuccess();
        } else {
            // 校验不通过
        }
    })
}

async function afterFormCheckSuccess() {
    let id = form.value.id
    let res = null;
    if (id) {
        // 修改
        res = await updateDeptById(form.value);
    } else {
        // 新增
        res = await addDept(form.value);
    }
    // 如果没有异常
    if (res.code) {
        // 弹框隐藏掉
        dialogFormVisible.value = false;
        // 刷新页面
        query();
    } else {
        // 有异常
        ElMessage.error(res.msg)
    }
}

// 修改逻辑
async function handleEdit(idx: number, row: DeptModel) {
    if (!row.id) {
        return;
    }
    // 展示弹框
    dialogFormVisible.value = true;
    dialogTitle.value = "修改部门"
    // 回显
    const res = await getDeptById(row.id);
    if (res.code) {
        form.value = res.data
    } else {
        ElMessage.error(res.msg)
    }
}

// 删除
function handleDelete(idx: number, row: DeptModel) {
    if (!row.id) {
        return;
    }
    // 删除提示框
    ElMessageBox.confirm('确认要删除此部门?', '', { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' })
        .then(async () => {
            // ElMessage({type: 'success',message: 'Delete completed',})
            // 确认删除，再调用删除接口
            const res = await deleteDeptById(row.id)
            if (res.code) {
                // 刷新页面
                query();
                ElMessage({ type: 'success', message: '删除成功', })
            } else {
                ElMessage.error(res.msg)
            }
        }).catch(() => {
            ElMessage({ type: 'error', message: 'Delete canceled', })
        })
}

// 表单校验
const rules = ref<FormRules<DeptModel>>({
    name: [
        { required: true, message: '部门名称不能为空', trigger: 'blur' },
        { min: 2, max: 10, message: '部门名称长度在2-10个字之间', trigger: 'blur' },
    ]
})
// 定义一个引用变量与form表单做绑定
const formRef = ref<FormInstance>()

// dialog关闭的时候自动回调
function dialogClose() {
    if (!formRef || !formRef.value) {
        return;
    }
    form.value = { name: '' }
    // 重置form校验规则
    formRef.value.resetFields();
}

</script>

<template>
    <span class="title">部门管理</span>
    <div class="addBtn"><el-button style="float:right;" type="primary" @click="openAdd">新增</el-button></div>
    <div class="deptTable">
        <el-table :data="deptList" border style="width: 100%">
            <el-table-column prop="id" label="序号" width="200" align="center" />
            <el-table-column prop="name" label="部门名称" width="300" align="center" />
            <el-table-column prop="updateTime" label="最后修改时间" width="300" align="center" />
            <el-table-column label="操作" align="center">
                <template #default="scope">
                    <el-button type="primary" @click="handleEdit(scope.$index, scope.row)">
                        修改
                    </el-button>
                    <el-button type="danger" @click="handleDelete(scope.$index, scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="400px" @close="dialogClose">
            <el-form :model="form" ref="formRef" :rules="rules">
                <el-form-item label="部门名称" prop="name">
                    <el-input v-model="form.name" autocomplete="off" style="width:90%" placeholder="请输入部门名称，长度2-10位" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="doAddOrUpdate(formRef)">保存</el-button>
                </div>
            </template>
        </el-dialog>


    </div>
</template>

<style scope>
.title {
    font-size: 20px;
    font-weight: 600;
}

.deptTable {
    margin-top: 30px
}

.addBtn {
    padding-right: 20px;
    padding-bottom: 20px;
}
</style>